
import { _decorator, Component, Node ,find ,TiledMap} from 'cc';
import {LogicManager} from "./logicManager";
import i18n from '../i18nMaster/runtime-scripts/LanguageData';
import {Constant} from "../framework/constant";
import {UIManager} from "../framework/uiManager";
import {PoolManager} from "../framework/poolManager";
import {GameState, Player, Prop} from "./GameState";
import {MgobeUtil} from "./mgobeUtil";
import {MapLogic} from "./mapLogic";
import {ClientEvent} from "../framework/clientEvent";
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = DisplayManager
 * DateTime = Sun Dec 19 2021 22:05:02 GMT+0800 (中国标准时间)
 * Author = yly1234560
 * FileBasename = displayManager.ts
 * FileBasenameNoExtension = displayManager
 * URL = db://assets/scripts/core/displayManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/zh/
 *
 */
 
@ccclass('DisplayManager')
export class DisplayManager extends Component {
    @property(LogicManager)
    public logicManager: LogicManager = null!;
    @property(MapLogic)
    public mapLogic: MapLogic = null!;

    @property(Node)
    public ready: Node = null!;
    @property(Node)
    public fight: Node = null!;


    public dicPlayers: {[index: string]: Node} = {};
    private _dicProps: {[index: number]: Node} = {};


    onEnable () {
        ClientEvent.on(Constant.EVENT_NAME.ON_GAME_START, this.gameStart, this);
        ClientEvent.on(Constant.EVENT_NAME.ON_GAME_END, this._onGameEnd, this);
    }

    onDisable () {
        ClientEvent.on(Constant.EVENT_NAME.ON_GAME_START, this.gameStart, this);
        ClientEvent.off(Constant.EVENT_NAME.ON_GAME_END, this._onGameEnd, this);
    }

    start () {
        i18n.init('zh');
        // AudioManager.instance.init();
        // WxAdapter.instance.start();
        this.reset();

        //@ts-ignore云函数入口函数
        // if (window.wx) {
        //     //@ts-ignore
        //     wx.cloud.init({
        //         traceUser: true,
        //         env: 'coinmgobe-9g7x0elue4e2224b'
        //     })
        //
        //     console.log("###cloud.init");
        //
        //     TcbManager.instance.onLoad();
        //     WxAdapter.instance.shareGame(Constant.GAME_NAME_CH, "");
        // }
    }

    /**
     * 开始游戏
     */
    public gameStart() {
        // AudioManager.instance.playMusic(Constant.AUDIO_NAME.BACKGROUND, true);
        // UIManager.instance.showDialog(Constant.PANEL_NAME.READY_GO, [()=>{
        //     UIManager.instance.showDialog(Constant.PANEL_NAME.FIGHT_UI, [this]);
        //     MgobeUtil.instance.startFrameSync();
        // }]);
        // UIManager.instance.hideDialog(Constant.PANEL_NAME.READY);

        /** yly 这里的重置需要显示准备ui 使用场景为 首页，暂未开发重新开始 start
         // UIManager.instance.hideDialog(Constant.PANEL_NAME.READY);
         */
        console.log("*****gameStart*******");

        this.ready.active = false;
        this.fight.active = true;

        // 初始化棋子
        ClientEvent.dispatchEvent(Constant.EVENT_MAP.INIT_PIECES);
        // 初始化开始战斗UI
        ClientEvent.dispatchEvent(Constant.FIGHT_UI.INIT_FIGHT_PLAYER);

        // 开启帧同步 棋牌类游戏不需要帧同步 暂时忽略掉
        // MgobeUtil.instance.startFrameSync();
        /** yly 这里的重置需要显示准备ui 使用场景为 首页，暂未开发重新开始 end */
    }


    /**
     * 重置游戏
     */
    public reset() {
        this.logicManager.setDefaultGameState();
        this._init();

        /** yly 这里的重置需要显示准备ui 使用场景为 首页，暂未开发重新开始 start
        // UIManager.instance.showDialog(Constant.PANEL_NAME.READY, [this]);
         */
        this.ready.active = true;
        // this.ready.active = false;
        this.fight.active = false;
        /** yly 这里的重置需要显示准备ui 使用场景为 首页，暂未开发重新开始 end */
    }

    /**
     * 显示初始场景
     */
    private _init() {
        // yly 如果有清空玩家和道具
        let keyArray: string[]= Object.keys(this.dicPlayers);
        keyArray.forEach((element: string)=> {
            PoolManager.instance.putNode(this.dicPlayers[parseInt(element)]);
            delete this.dicPlayers[parseInt(element)];
        });
        keyArray= Object.keys(this._dicProps);
        keyArray.forEach((element: string)=> {
            PoolManager.instance.putNode(this._dicProps[parseInt(element)]);
            delete this._dicProps[parseInt(element)];
        });


        // yly 清空后添加玩家和道具
        let gameState: GameState = this.logicManager.currentGameState;
        let players: Array<Player> = gameState.players;
        players.forEach((value: Player, index: number) => {
            // let node: Node = PoolManager.instance.getNode(this.playerPrefab, this.playerGroupNode);
            // node.setWorldPosition(value.position);
            // node.eulerAngles = value.eulerAngles;
            // node.getComponent(Fighter)?.init(this, index);

            // let node = find("Canvas/fight") as Node;
            // node.getComponent(Fighter)?.init(this, index);
            // this.dicPlayers[index] = node;
        })

        // let props: Array<Prop> = gameState.props;
        // props.forEach((value: Prop, index: number) => {
            // this._dicProps[index] = this._createProp(value);
        // });
    }


    /**
     * 游戏开始事件回调
     */
    private _onGameStart() {
        // AudioManager.instance.playMusic(Constant.AUDIO_NAME.BACKGROUND, true);
        UIManager.instance.showDialog(Constant.PANEL_NAME.FIGHT_UI, [this]);
        UIManager.instance.hideDialog(Constant.PANEL_NAME.READY);
    }

    /**
     * 游戏结束事件回调
     */
    private _onGameEnd () {
        // AudioManager.instance.playSound(Constant.AUDIO_NAME.TIME_OUT);

        // UIManager.instance.hideDialog(Constant.PANEL_NAME.FIGHT_UI);
        // let winner = -1;
        // let dictScore: {[index: number]: number} = {} as {[index: number]: number};
        // let players: Player[] = this.logicManager.currentGameState.players;
        //
        // players.forEach((player: Player, idx: number)=>{
        //     if (player.isScoreLead) {
        //         winner = player.id;
        //     }
        //
        //     dictScore[idx] = player.score;
        // })
        //
        // if (winner === -1) {
        //     winner = 0; //异常就第一个玩家获得胜利
        // }
        //
        // UIManager.instance.showDialog(Constant.PANEL_NAME.GAME_OVER, [this, dictScore, winner]);

        console.log("****** game over ******");
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.3/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.3/manual/zh/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.3/manual/zh/scripting/life-cycle-callbacks.html
 */
